#!/usr/bin/perl 
#
#Check HOME
# Este script fara um check na home, verificando integridade de links de diversas urls da home. 

use strict ;
use IO::Socket;
use File::Basename;
use Sys::Hostname;
use WWW::Mechanize ;
use Time::HiRes qw ( time );



my $logDate = `/bin/date +%Y%m%d`;
chomp $logDate ;

my $errorLog = "/export/logs/monit_Time-${logDate}.log";

my $hostname .= "check_home.adm.uol.intranet";
my $scriptname=basename("$0");

my %urls = ();
my %url_times = ();

my $TRUE = 0 ;
my $FALSE = 1; 

my $CONFIG_FILE = "/home/gassad/url_list.txt" ; 

my $TEMP_FILE = "/tmp/url_temp_get.html";

sub timestamp
{
    my $tstamp = `date +'%Y%m%d %H:%M:%S'` ;
    chomp $tstamp ; 

    return ( $tstamp );
}

sub printResult ()
{
   my $msg = shift();
  
   my $tstamp = timestamp();


   my $message = "$tstamp\;$msg";

   #my $out = `/bin/logger -p local5.info \"$message\"`;

   open ( ERRORLOG, ">>$errorLog" ) or die "Can't write to file: $!";
   print  ERRORLOG "$message\n";
   close ( ERRORLOG );

   print "$message\n";
}

sub abortResult ()
{
   my $msg = shift();

   my $tstamp = timestamp();


   my $message = "$tstamp PROCESS_SERVICE_CHECK_RESULT;$hostname;Check Full HOME;$msg";

   #my $out = `/bin/logger -p local5.info \"$message\"`;

   #open ( ERRORLOG, ">>$errorLog" ) or die "Can't write to file: $!";
   #print  ERRORLOG "$message";
   #close ( ERRORLOG );

   print "$message\n";
   die "$message\n";
}

sub checkUrl($)
{
   my $url = shift(); 

   my $latency =  0; 
   my $size = 0;

   ## Usa o mechanize para baixar a home e separar links
   my $mech = WWW::Mechanize->new();

   my $start = time();
   $mech->get("$url");
   my $end = time();

   if ( $mech->status == 200 ) 
   {
      $latency = sprintf("%.3f", $end - $start) ; 
      $mech->save_content("$TEMP_FILE");
      $size = (stat($TEMP_FILE))[7]; 
   }
   else
   {
      $latency = "-1"; 
      $size = "-1"; 
   }

   return($latency,$size);
}

open (CONF,"<$CONFIG_FILE") or die "Can't open file: $!\n" ; 

while (<CONF>)
{

   next if ( $_ !~ /.\s./ );
   chomp $_ ; 

   my ($param,$url ) = split ( /\s/, $_ );

   $urls{$param} = $url ;  
}
   
foreach my $param (keys %urls )
{
   my $url = $urls{$param} ; 


   my ($timeSpent,$fileSize) = checkUrl($url); 

   $url_times{$param} = "$timeSpent;$fileSize;"; 
}

my $Message = "";

foreach my $url (sort keys %url_times )
{

   $Message = $Message . "$url\;$url_times{$url}"; 

}

&printResult ("$Message");
